/*
 * @(#)cn.design.pattern.prototype.deep 2020/4/10/0010
 *
 * Copy Right@ 人人译视界
 */


package cn.design.pattern.prototype.deep;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/10/0010
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class DeepPrototype implements Serializable, Cloneable {
	public String name;
	public DeepClonableTarget deepClonableTarget;

	public DeepPrototype() {
	}

	/**
	 * 深拷贝——方法1：重写clone
	 *
	 * @return
	 * @throws CloneNotSupportedException
	 */
	@Override
	protected Object clone() throws CloneNotSupportedException {
		Object deep = null;
		// 完成对基本属性的clone
		deep = super.clone();
		// 对引用类型单独处理
		DeepPrototype deepPrototype = (DeepPrototype) deep;
		deepPrototype.deepClonableTarget = (DeepClonableTarget) deepClonableTarget.clone();
		return deep;
	}

	/**
	 * 深拷贝——方法2：通过对象序列化来实现(推荐)
	 */
	public Object deepClone() {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);// 把当前的对象以对象流的方式输出

			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			Object obj = ois.readObject();
			return obj;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			try {
				bos.close();
				bis.close();
				oos.close();
				ois.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
